package day10;

import java.util.Random;

public class Homework4 {
    static String product="产品";
    static int maxnum=100;
    static int nownum=100;
    public synchronized void printA(){
        Random random = new Random();
        int r1 = random.nextInt(99)+1;
        if(r1<=nownum){
            nownum=nownum-r1;
            System.out.println("消费者购买"+r1+"个,剩余"+nownum+"个");
        }else{
            System.out.println("库存不足"+r1+"个,正在生产");
            try {
                this.notifyAll();
                this.wait();
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        }
    }
    public synchronized void printB(){
        if(nownum<maxnum){
            nownum=maxnum-nownum;
            System.out.println("可以购买了");
            try {
                this.notifyAll();
                this.wait();
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        }
    }
    public static void main(String[] args) {
        Homework4 h=new Homework4();
        new Thread(()->{
            while (true){
                h.printA();
            }
        },"消费者").start();
        new Thread(()->{
            while (true){
                h.printB();
            }
        },"生产者").start();
    }
}
